package com.activitiFlow.service.impl;

import java.util.HashMap;
import java.util.Map;

import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.activitiFlow.service.IRuntimeBiz;
import com.activitiFlow.service.ITaskBiz;
import com.vx.FlowCode;

@Service("runtimeBiz")
public class RuntimeBizImpl implements IRuntimeBiz {
	
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private TaskService taskService;
	
	@Override
	public ProcessInstance saveStartProcess(String borrowId, String processKey,String transactor ) {
		
		Map<String,Object> variables=new HashMap<String,Object>();
		variables.put(FlowCode.USERCODE, transactor);
		variables.put("objId",processKey+"."+borrowId);
		//使用流程定义的key，启动流程实例，同时设置流程变量，
		//同时向正在执行的执行对象表中的字段BUSINESS_KEY添加业务数据，同时让流程关联业务
		ProcessInstance processInstance=runtimeService.startProcessInstanceByKey(processKey, processKey+"."+borrowId, variables);
		return processInstance;
	}
	

	@Override
	public ProcessInstance getProcessInstanceById(String processInstanceId) {
		return runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
	}
	
	@Override
	public String getBusinessIdByTaskId(String taskId) {
		ProcessInstance processInstance=this.getProcessInstanceById(taskService.createTaskQuery().taskId(taskId).singleResult().getProcessInstanceId());
		String businessKey=processInstance.getBusinessKey();
		String borrowId=businessKey.substring(businessKey.indexOf(".")+1);
		return borrowId;
	}
	

	@Override
	public void removeVariable(String executionId, String usercode) {
		runtimeService.removeVariable(executionId,usercode);
	}


}
